/**
 * 
 */
package edu.hunau.dom4j;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Before;
import org.junit.Test;

/**
 * 
 * @author hb
 */
public class XpathDemo {

	private Document document;

	@Before
	public void init() {
		SAXReader reader = new SAXReader();
		try {
			document = reader.read("./src/main/resources/books.xml");
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}
	}

	@Test
	public void readAllPrcie() {
		List<Node> nodes = document.selectNodes("/books/book/price");
		for (Node node : nodes) {
			System.out.println(node.getText());
		}
	}

	@Test
	public void readAllName() {
		// List<Node> nodes = document.selectNodes("/books/book//name");
		List<Node> nodes = document.selectNodes("//name");
		for (Node node : nodes) {
			System.out.println(node.getText());
		}
	}

	@Test
	public void readBookIdAtt() {
		List<Node> nodes = document.selectNodes("/books/book/@id");
		for (Node node : nodes) {
			System.out.println(node.getName() + "  =  " + node.getStringValue());
		}
	}

	@Test
	// 根据属性值获得book
	public void readBookById() {
		List<Node> nodes = document.selectNodes("/books/book[@id='1002']");
		for (Node node : nodes) {
			Element el = (Element) node;
			System.out.println(el.elementText("name"));
		}
	}

	@Test // 根据作者查询书籍
	public void readBookByAutor() {
		List<Node> nodes = document.selectNodes("/books/book[author/name='二月河']");
		for (Node node : nodes) {
			Element el = (Element) node;
			System.out.println(el.elementText("name"));
		}

	}

	@Test
	public void readBookByPrcie() {

		List<Node> nodes = document.selectNodes(" /books/book[price>'100']");
		for (Node node : nodes) {
			Element el = (Element) node;
			System.out.println(el.elementText("name"));
		}
	}

	@Test // 根据位置查询信息
	public void readBookPosition() {
		List<Node> nodes = document.selectNodes("/books/book[position()<=2]/name");
		for (Node node : nodes) {

			System.out.println(node.getStringValue());
		}
	}
}
